package com.myblog.config.security;

import com.myblog.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class VerifyCodeFilter extends OncePerRequestFilter implements Filter {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 必须是登录的post请求才能进行验证，其他的直接放行
        if (request.getRequestURI().equalsIgnoreCase("/login") && request.getMethod().equalsIgnoreCase("POST")) {

            String form_verifyCode = request.getParameter("verifyCode");
            String verifyCode = (String) redisUtil.get("BLOG:verifyCode:" + form_verifyCode.toUpperCase());
            //因为全局异常处理器只抓取Controller层的异常，所以转发到controller层
            if (StringUtils.isEmpty(form_verifyCode)) {
                request.getRequestDispatcher("/verify/null").forward(request, response);
                return;
            }
            if (StringUtils.isEmpty(verifyCode)) {
                request.getRequestDispatcher("/verify/error").forward(request, response);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

}
